package com.insurance.controller;

import com.google.code.kaptcha.Producer;
import com.insurance.constant.ConstantData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 获取验证码控制器
 *
 * @version 1.0
 * @date 2020/10/19
 **/
@Slf4j
@Controller
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private Producer producer;

    @GetMapping("/generateCode")
    public void generateCode(HttpServletResponse response, @RequestParam Long randomCode){
        try {
            response.setHeader("Cache-Control", "no-store, no-cache");
            response.setContentType("image/jpeg");
            //生成随机串
            String validateCode = producer.createText();
            //将随机串放入缓存中
            ConstantData.validateCodeMap.put(randomCode, validateCode);
            BufferedImage bufferedImage = producer.createImage(validateCode);
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(bufferedImage, "jpg", out);
            IOUtils.closeQuietly(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
